package com.wxy.ej.nosql.modules.excel.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rt.easyjava.common.base.Result;
import com.wxy.ej.nosql.modules.excel.entity.WorkBookEntity;
import com.wxy.ej.nosql.modules.excel.entity.WorkSheetEntity;
import com.wxy.ej.nosql.modules.excel.repository.WorkBookRepository;
import com.wxy.ej.nosql.modules.excel.repository.WorkSheetRepository;
import com.wxy.ej.nosql.modules.excel.utils.SheetUtil;
import jdk.nashorn.internal.scripts.JO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @date 2020/10/28
 * @description
 */
@RequestMapping("/excel")
@RestController
public class WorkBookController {

    @Autowired
    private WorkBookRepository workBookRepository;

    @Autowired
    private WorkSheetRepository workSheetRepository;
    /*
    @GetMapping("index")
    public ModelAndView index() {
        List<WorkBookEntity> all = workBookRepository.findAll();

        return new ModelAndView("index", "all", all);
    }*/


    @PostMapping("/create")
    public Result create(@RequestBody Map<String, String> paramMap)  {
        String fileId = paramMap.get("fileId");
        String name = paramMap.get("name");
        if (fileId==null) {
            return Result.builder().fault("fileId="+fileId);
        }

        WorkBookEntity wb = new WorkBookEntity();
        String wbId = fileId;
        wb.setId(wbId);
        wb.setName(name);
        wb.setCreatedTime(DateTime.now());
        wb.setOption(SheetUtil.getDefautOption());
        workBookRepository.save(wb);
        //生成sheet数据
        generateSheet(wbId);
        return Result.builder(wbId);
    }


    @PostMapping("/backupData")
    public Result backupData(@RequestBody Map<String, String> paramMap)  {
        String pFileId = paramMap.get("pFileId");
        String fileId = paramMap.get("fileId");
        String name = paramMap.get("name");
        String wbId = fileId;

        WorkBookEntity wb = new WorkBookEntity();
        wb.setId(wbId);
        wb.setName(name);
        wb.setCreatedTime(DateTime.now());
        wb.setOption(SheetUtil.getDefautOption());
        workBookRepository.save(wb);

        // 查询sheet列表
        List<WorkSheetEntity> sheetList = workSheetRepository.findAllBywbId(pFileId);
        for (WorkSheetEntity sheet: sheetList) {
            // backup sheet
            WorkSheetEntity ws = new WorkSheetEntity();
            ws.setId(IdUtil.simpleUUID());
            ws.setWbId(wbId);
            ws.setData(sheet.getData());
            ws.setCreatedTime(DateTime.now());
            ws.setDeleteStatus(sheet.getDeleteStatus());
            workSheetRepository.save(ws);
        }

        return Result.builder(wbId);
    }


    @PostMapping("/load/{wbId}")
    public String load(@PathVariable(value = "wbId") String wbId) {
        List<WorkSheetEntity> wsList = workSheetRepository.findAllBywbId(wbId);
        List<JSONObject> list = new ArrayList<>();
        wsList.forEach(ws -> {
            list.add(ws.getData());
        });

        return JSONUtil.toJsonStr(list);
        //return "[{\"hyperlink\":{},\"column\":60,\"index\":\"d6df4d245b7d4535869703dce2c8210e\",\"luckysheet_alternateformat_save\":{},\"calcChain\":[],\"dataVerification\":{},\"name\":\"sheet1\",\"luckysheet_conditionformat_save\":{},\"celldata\":[{\"r\":178,\"c\":1,\"v\":{\"ct\":{\"t\":\"g\",\"fa\":\"General\"},\"v\":\"dd\",\"m\":\"dd\"}}],\"row\":184,\"config\":{\"merge\":{}},\"order\":0,\"status\":1},{\"column\":60,\"name\":\"sheet2\",\"index\":\"6126419de5cc4bca864434a6a0b5fdf7\",\"celldata\":[],\"row\":84,\"order\":1,\"status\":0},{\"column\":60,\"name\":\"sheet3\",\"index\":\"97c4a00799ef44188bfbf453db4ad7da\",\"celldata\":[],\"row\":84,\"order\":2,\"status\":0}]";
    }


    @PostMapping("/loadSheet/{wbId}")
    public String loadSheet(@PathVariable(value = "wbId") String wbId) {
        List<WorkSheetEntity> wsList = workSheetRepository.findAllBywbId(wbId);
        List<JSONObject> list = new ArrayList<>();
        wsList.forEach(ws -> {
            list.add(ws.getData());
        });
        if (!list.isEmpty()) {
            return SheetUtil.buildSheetData(list).toString();
        }
        return SheetUtil.getDefaultAllSheetData().toString();
    }


    private void generateSheet(String wbId) {
        SheetUtil.getDefaultSheetData().forEach(jsonObject -> {
            WorkSheetEntity ws = new WorkSheetEntity();
            ws.setId(IdUtil.simpleUUID());
            ws.setWbId(wbId);
            ws.setData(jsonObject);
            ws.setCreatedTime(DateTime.now());
            ws.setDeleteStatus(0);
            workSheetRepository.save(ws);
        });
    }

    @PostMapping("/importExcel")
    public Result importExcel(@RequestBody Map<String, String> paramMap)  {
        String paramKey = paramMap.get("paramKey");
        Object luckysheetfile = paramMap.get("luckysheetfile");

        // 删除原sheet
        List<WorkSheetEntity> wsList = workSheetRepository.findAllBywbId(paramKey);
        wsList.forEach(ws -> {
            // workSheetRepository.delete(ws);
            ws.setDeleteStatus(1);
            workSheetRepository.save(ws);
        });

        // 插入新的sheet
        JSONObject luckysheetfileJo = new JSONObject(luckysheetfile);
        JSONObject info = luckysheetfileJo.getJSONObject("info");
        String fileName = info.getStr("name");

        JSONArray sheets = luckysheetfileJo.getJSONArray("sheets");
        for (int i=0;i<sheets.size();i++) {
            JSONObject sheet = sheets.getJSONObject(i);
            String sheetIndex = IdUtil.simpleUUID();
            //sheet.put("", sheetIndex);
            WorkSheetEntity ws = new WorkSheetEntity();
            ws.setId(IdUtil.simpleUUID());
            ws.setWbId(paramKey);
            ws.setData(sheet);
            ws.setCreatedTime(DateTime.now());
            ws.setDeleteStatus(0);
            workSheetRepository.save(ws);
        }

        return Result.builder();
    }


}
